package com.hmdp.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_TTL;

/**
 * @author jay
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryListType() {
        //从redis中查询
        List<String> range = stringRedisTemplate.opsForList().range(CACHE_SHOPTYPE_KEY, 0, -1);
        List<ShopType> shopTypes;
        //存在 封装 返回
        //判断集合是否为空或null  使用hutools的CollUtil
        if (CollUtil.isNotEmpty(range)) {
            //更新时间
            stringRedisTemplate.expire(CACHE_SHOPTYPE_KEY, CACHE_SHOPTYPE_TTL, TimeUnit.MINUTES);
            //这里不懂可以查询lambda
            shopTypes = range.stream().map(item -> JSONUtil.toBean(item, ShopType.class)).collect(Collectors.toList());
            return Result.ok(shopTypes);
        }
        //不存在 从数据库中查询
        List<ShopType> sort = query().orderByAsc("sort").list();
        //数据库不存在 返回错误
        if (CollUtil.isEmpty(sort)) {
            return Result.fail("不存在");
        }
        //存在 存入redis，并设置过期时间
        stringRedisTemplate.opsForList().rightPushAll(CACHE_SHOPTYPE_KEY, sort.stream().map(item -> JSONUtil.toJsonStr(item)).collect(Collectors.toList()));
        stringRedisTemplate.expire(CACHE_SHOPTYPE_KEY, CACHE_SHOPTYPE_TTL, TimeUnit.MINUTES);
        //返回
        return Result.ok(sort);


    }
}
